if...else statement
Decision making is an important part of programming. This can be achieved in R programming using the conditional if...else
statement.
if
statement
Syntax of if
statement
if (test_expression) {
statement
}
If the test_expression
is TRUE
, the statement gets executed. But if it's FALSE
, nothing happens. Here, test_expression
can be a logical or numeric vector, but only the first element is taken into consideration. In the case of numeric vector, zero is taken as FALSE
, rest as TRUE
.
Flowchart of if
statement
Example of if
statement
x <- 5
if(x > 0){
print("Positive number")
}
Output
[1] "Positive number"
if...else
statement
Syntax of if...else
statement
if (test_expression) {
statement1
} else {
statement2
}
The else
part is optional and is evaluated if test_expression
is FALSE
. It is important to note that else
must be in the same line as the closing braces of the if
statements.
Flowchart of if...else
statement
Example of if...else
statement
x <- -5
if(x > 0){
print("Non-negative number")
} else {
print("Negative number")
}
Output
[1] "Negative number"
The above conditional can also be written in a single line as follows.
if(x > 0) print("Non-negative number") else print("Negative number")
This feature of R allows us to write construct as shown below.
> x <- -5
> y <- if(x > 0) 5 else 6
> y
[1] 6
Nested if...else
statement
We can nest as many if...else
statement as we want as follows.
Syntax of nested if...else
statement
if ( test_expression1) {
statement1
} else if ( test_expression2) {
statement2
} else if ( test_expression3) {
statement3
} else
statement4
Only one statement will get executed depending upon the test_expressions.
Example of nested if...else
statement
x <- 0
if (x < 0) {
print("Negative number")
} else if (x > 0) {
print("Positive number")
} else
print("Zero")
Output
[1] "Zero"